#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //创建3行
    ui->tableWidget->insertRow(0);//插入第0行，注意是和数组下标一样的
    ui->tableWidget->insertRow(1);
    ui->tableWidget->insertRow(2);

    //创建3列
    ui->tableWidget->insertColumn(0);
    ui->tableWidget->insertColumn(1);
    ui->tableWidget->insertColumn(2);

    //给3列设定列名称（即设置水平方向的表头）
    ui->tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("学号"));
    ui->tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("姓名"));
    ui->tableWidget->setHorizontalHeaderItem(2,new QTableWidgetItem("年龄"));

    //表中添加数据
    ui->tableWidget->setItem(0,0,new QTableWidgetItem("1001"));
    ui->tableWidget->setItem(0,1,new QTableWidgetItem("张三"));
    ui->tableWidget->setItem(0,2,new QTableWidgetItem("20"));

    ui->tableWidget->setItem(1,0,new QTableWidgetItem("1002"));
    ui->tableWidget->setItem(1,1,new QTableWidgetItem("李四"));
    ui->tableWidget->setItem(1,2,new QTableWidgetItem("19"));

    ui->tableWidget->setItem(2,0,new QTableWidgetItem("1003"));
    ui->tableWidget->setItem(2,1,new QTableWidgetItem("王五"));
    ui->tableWidget->setItem(2,2,new QTableWidgetItem("20"));

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_insertColumn_clicked()
{
    //先获取一共有多少列
    int colCount = ui->tableWidget->columnCount();
    //在获取到的位置新增一列
    ui->tableWidget->insertColumn(colCount);
    //设置列名（要求从输入框Line Edit中获取）
    const QString& text = ui->lineEdit->text();
    ui->tableWidget->setHorizontalHeaderItem(colCount,new QTableWidgetItem(text));
}

void Widget::on_pushButton_insertRow_clicked()
{
    int rowCount = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(rowCount);
}

void Widget::on_pushButton_deleteRow_clicked()
{
    int curRow = ui->tableWidget->currentRow();//注意删除选中行和新增行使用的函数是不同的
    ui->tableWidget->removeRow(curRow);
}


void Widget::on_pushButton_deleteColumn_clicked()
{
    int curCol = ui->tableWidget->currentColumn();
    ui->tableWidget->removeColumn(curCol);
}
